package com.itheima.reggie.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.reggie.common.BaseConText;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.UserDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;
import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")
@Slf4j
public class LoginCheckFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws ServletException, IOException {
        log.info("拦截到请求");
        //把请求路径转化为http协议
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        HttpServletResponse response= (HttpServletResponse) servletResponse;
        String requestURI = request.getRequestURI();
       //定义不能拦截的路径
        String [] urls={
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/sendMsg",
                "/user/login",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"
        };
        //判断路径是否为不能拦截资源
        boolean check=check(urls,requestURI);
        if (check){
            chain.doFilter(servletRequest,servletResponse);
            return;
        }
        Long employee = (Long) request.getSession().getAttribute("employee");
        if (employee!=null){
            chain.doFilter(servletRequest,servletResponse);
            return;
        }
        UserDto userDto = (UserDto) request.getSession().getAttribute("user");
        if (userDto!=null){
            BaseConText.setCurrentId(userDto.getId());
            chain.doFilter(servletRequest,servletResponse);
            return;
        }
        response.setContentType("text/json;charset=utf-8");//设置响应类型
        R<String> r = R.error("NOTLOGIN");
        String jsonStr = new ObjectMapper().writeValueAsString(r);
        log.info(jsonStr);
        response.getWriter().write(jsonStr);//响应json数据
    }
    //spring框架提供的路径匹配工具类
    AntPathMatcher pathMatcher=new AntPathMatcher();
    private boolean check(String [] urls,String requestURI){
        for (String url : urls) {
            boolean match = pathMatcher.match(url, requestURI);
            if (match){
                return true;
            }
        }return false;
    }

}
